/**
 * 统一手势处理器
 * 合并所有手势识别和处理逻辑，消除重复代码
 */

import * as THREE from 'three';

export class UnifiedGestureHandler {
    constructor(xrManager, options = {}) {
        this.xrManager = xrManager;
        
        // 配置选项
        this.options = {
            gestureThreshold: 0.7,
            pinchThreshold: 0.02,
            pointThreshold: 0.08,
            palmThreshold: 0.07,
            swipeMinDistance: 0.1,
            swipeMaxTime: 800,
            gestureFrameRate: 30,
            enableHapticFeedback: true,
            enableVisualFeedback: true,
            ...options
        };
        
        // 手势状态
        this.gestureStates = new Map();
        this.gestureHistory = [];
        this.activeGestures = new Set();
        this.lastGestureUpdate = 0;
        
        // 手势配置
        this.gestureConfig = {
            pinch: {
                threshold: this.options.pinchThreshold,
                holdTime: 100,
                repeatDelay: 200
            },
            point: {
                threshold: this.options.pointThreshold,
                stabilityTime: 500,
                maxDeviation: 0.01
            },
            palm: {
                threshold: this.options.palmThreshold,
                openFingers: 4,
                confidence: 0.8
            },
            swipe: {
                minDistance: this.options.swipeMinDistance,
                maxTime: this.options.swipeMaxTime,
                minVelocity: 0.2
            }
        };
        
        // 手势回调
        this.gestureCallbacks = new Map();
        
        // 性能优化
        this.frameCount = 0;
        this.shouldUpdateVisualization = () => this.frameCount % 2 === 0;
        
        this.init();
    }
    
    init() {
        console.log('🎯 初始化统一手势处理器');
        
        // 注册默认手势处理器
        this.registerDefaultGestureHandlers();
        
        // 监听XR管理器事件
        this.xrManager.addEventListener('xr-session-start', this.onXRSessionStart.bind(this));
        this.xrManager.addEventListener('xr-session-end', this.onXRSessionEnd.bind(this));
    }
    
    onXRSessionStart() {
        console.log('手势处理器：XR会话开始');
        this.startGestureRecognition();
    }
    
    onXRSessionEnd() {
        console.log('手势处理器：XR会话结束');
        this.stopGestureRecognition();
    }
    
    registerDefaultGestureHandlers() {
        // 注册默认的手势处理器
        this.registerGestureHandler('pinch', this.handlePinchGesture.bind(this));
        this.registerGestureHandler('point', this.handlePointGesture.bind(this));
        this.registerGestureHandler('palm', this.handlePalmGesture.bind(this));
        this.registerGestureHandler('swipe', this.handleSwipeGesture.bind(this));
        this.registerGestureHandler('tap', this.handleTapGesture.bind(this));
        this.registerGestureHandler('thumbsup', this.handleThumbsUpGesture.bind(this));
        this.registerGestureHandler('peace', this.handlePeaceGesture.bind(this));
        this.registerGestureHandler('fist', this.handleFistGesture.bind(this));
        this.registerGestureHandler('ok', this.handleOKGesture.bind(this));
    }
    
    registerGestureHandler(gestureType, handler) {
        if (!this.gestureCallbacks.has(gestureType)) {
            this.gestureCallbacks.set(gestureType, []);
        }
        this.gestureCallbacks.get(gestureType).push(handler);
    }
    
    unregisterGestureHandler(gestureType, handler) {
        if (this.gestureCallbacks.has(gestureType)) {
            const handlers = this.gestureCallbacks.get(gestureType);
            const index = handlers.indexOf(handler);
            if (index > -1) {
                handlers.splice(index, 1);
            }
        }
    }
    
    startGestureRecognition() {
        console.log('🎯 开始手势识别');
        this.gestureRecognitionActive = true;
        this.gestureRecognitionLoop();
    }
    
    stopGestureRecognition() {
        console.log('🛑 停止手势识别');
        this.gestureRecognitionActive = false;
    }
    
    gestureRecognitionLoop() {
        if (!this.gestureRecognitionActive || !this.xrManager.isXRActive) {
            return;
        }
        
        // 性能优化：帧率控制
        const now = performance.now();
        if (!this.lastGestureUpdate) this.lastGestureUpdate = now;
        
        const deltaTime = now - this.lastGestureUpdate;
        const targetFrameTime = 1000 / this.options.gestureFrameRate;
        
        if (deltaTime >= targetFrameTime) {
            // 更新手部数据
            this.updateHandData();
            
            // 识别手势
            this.recognizeGestures();
            
            // 更新可视化（降低频率）
            if (this.options.enableVisualFeedback && this.shouldUpdateVisualization()) {
                this.updateVisualFeedback();
            }
            
            this.lastGestureUpdate = now;
            this.frameCount++;
        }
        
        // 继续循环
        requestAnimationFrame(() => this.gestureRecognitionLoop());
    }
    
    updateHandData() {
        // 从XR管理器获取手部数据
        const handJoints = this.xrManager.handJoints;
        const handPoses = this.xrManager.handPoses;
        
        // 更新手势状态
        for (const [handedness, joints] of handJoints) {
            const pose = handPoses.get(handedness);
            if (!pose) continue;
            
            // 更新手势状态
            this.updateGestureState(handedness, joints, pose);
        }
    }
    
    updateGestureState(handedness, joints, pose) {
        if (!this.gestureStates.has(handedness)) {
            this.gestureStates.set(handedness, {
                currentGesture: null,
                gestureStartTime: 0,
                gestureHistory: [],
                lastPosition: new THREE.Vector3(),
                velocity: new THREE.Vector3()
            });
        }
        
        const state = this.gestureStates.get(handedness);
        
        // 计算手部速度
        const wristJoint = joints.get('wrist');
        if (wristJoint) {
            const currentPosition = wristJoint.position.clone();
            state.velocity.subVectors(currentPosition, state.lastPosition);
            state.lastPosition.copy(currentPosition);
        }
    }
    
    recognizeGestures() {
        // 检查每只手的手势
        for (const [handedness, joints] of this.xrManager.handJoints) {
            const pose = this.xrManager.handPoses.get(handedness);
            if (!pose) continue;
            
            // 检测各种手势
            this.detectAndProcessGesture('pinch', handedness, joints, pose);
            this.detectAndProcessGesture('point', handedness, joints, pose);
            this.detectAndProcessGesture('palm', handedness, joints, pose);
            this.detectAndProcessGesture('swipe', handedness, joints, pose);
            this.detectAndProcessGesture('tap', handedness, joints, pose);
            this.detectAndProcessGesture('thumbsup', handedness, joints, pose);
            this.detectAndProcessGesture('peace', handedness, joints, pose);
            this.detectAndProcessGesture('fist', handedness, joints, pose);
            this.detectAndProcessGesture('ok', handedness, joints, pose);
        }
    }
    
    detectAndProcessGesture(gestureType, handedness, joints, pose) {
        let gestureData = null;
        
        switch (gestureType) {
            case 'pinch':
                gestureData = this.detectPinchGesture(joints, pose);
                break;
            case 'point':
                gestureData = this.detectPointGesture(joints, pose);
                break;
            case 'palm':
                gestureData = this.detectPalmGesture(joints, pose);
                break;
            case 'swipe':
                gestureData = this.detectSwipeGesture(joints, pose, handedness);
                break;
            case 'tap':
                gestureData = this.detectTapGesture(joints, pose, handedness);
                break;
            case 'thumbsup':
                gestureData = this.detectThumbsUpGesture(joints, pose);
                break;
            case 'peace':
                gestureData = this.detectPeaceGesture(joints, pose);
                break;
            case 'fist':
                gestureData = this.detectFistGesture(joints, pose);
                break;
            case 'ok':
                gestureData = this.detectOKGesture(joints, pose);
                break;
        }
        
        if (gestureData && gestureData.detected) {
            this.processGesture(gestureType, handedness, gestureData, joints);
        }
    }
    
    // 手势检测方法（简化版本）
    detectPinchGesture(joints, pose) {
        const thumbTip = joints.get('thumb-tip');
        const indexTip = joints.get('index-finger-tip');
        
        if (!thumbTip || !indexTip) {
            return { detected: false };
        }
        
        const distance = thumbTip.position.distanceTo(indexTip.position);
        const detected = distance < this.gestureConfig.pinch.threshold;
        
        return {
            detected,
            confidence: detected ? Math.max(0, 1 - distance / this.gestureConfig.pinch.threshold) : 0,
            distance,
            position: thumbTip.position.clone().lerp(indexTip.position, 0.5)
        };
    }
    
    detectPointGesture(joints, pose) {
        const indexTip = joints.get('index-finger-tip');
        const indexMcp = joints.get('index-finger-metacarpal');
        const middleTip = joints.get('middle-finger-tip');
        
        if (!indexTip || !indexMcp || !middleTip) {
            return { detected: false };
        }
        
        // 检查食指是否伸直，其他手指是否弯曲
        const indexExtended = indexTip.position.distanceTo(indexMcp.position) > this.gestureConfig.point.threshold;
        const middleBent = middleTip.position.distanceTo(indexMcp.position) < this.gestureConfig.point.threshold;
        
        const detected = indexExtended && middleBent;
        
        return {
            detected,
            confidence: detected ? 0.8 : 0,
            direction: new THREE.Vector3().subVectors(indexTip.position, indexMcp.position).normalize(),
            position: indexTip.position.clone()
        };
    }
    
    detectPalmGesture(joints, pose) {
        // 简化的手掌检测
        const wrist = joints.get('wrist');
        const thumbTip = joints.get('thumb-tip');
        const indexTip = joints.get('index-finger-tip');
        const middleTip = joints.get('middle-finger-tip');
        const ringTip = joints.get('ring-finger-tip');
        const pinkyTip = joints.get('pinky-finger-tip');
        
        if (!wrist || !thumbTip || !indexTip || !middleTip || !ringTip || !pinkyTip) {
            return { detected: false };
        }
        
        // 检查所有手指是否都伸展
        const fingerTips = [thumbTip, indexTip, middleTip, ringTip, pinkyTip];
        const allExtended = fingerTips.every(tip => 
            tip.position.distanceTo(wrist.position) > this.gestureConfig.palm.threshold
        );
        
        return {
            detected: allExtended,
            confidence: allExtended ? 0.8 : 0,
            position: wrist.position.clone()
        };
    }
    
    detectSwipeGesture(joints, pose, handedness) {
        const state = this.gestureStates.get(handedness);
        if (!state) return { detected: false };
        
        const velocity = state.velocity;
        const speed = velocity.length();
        
        if (speed > this.gestureConfig.swipe.minVelocity) {
            let direction = 'unknown';
            
            if (Math.abs(velocity.x) > Math.abs(velocity.y)) {
                direction = velocity.x > 0 ? 'right' : 'left';
            } else {
                direction = velocity.y > 0 ? 'up' : 'down';
            }
            
            return {
                detected: true,
                confidence: Math.min(1, speed / (this.gestureConfig.swipe.minVelocity * 2)),
                direction,
                velocity: velocity.clone(),
                speed
            };
        }
        
        return { detected: false };
    }
    
    detectTapGesture(joints, pose, handedness) {
        // 简化的点击检测
        const indexTip = joints.get('index-finger-tip');
        if (!indexTip) return { detected: false };
        
        const state = this.gestureStates.get(handedness);
        if (!state) return { detected: false };
        
        const speed = state.velocity.length();
        const isQuickMovement = speed > 0.5 && speed < 2.0;
        
        return {
            detected: isQuickMovement,
            confidence: isQuickMovement ? 0.7 : 0,
            position: indexTip.position.clone()
        };
    }
    
    detectThumbsUpGesture(joints, pose) {
        // 简化的竖拇指检测
        const thumbTip = joints.get('thumb-tip');
        const thumbMcp = joints.get('thumb-metacarpal');
        const indexTip = joints.get('index-finger-tip');
        
        if (!thumbTip || !thumbMcp || !indexTip) {
            return { detected: false };
        }
        
        // 检查拇指是否向上伸展
        const thumbUp = thumbTip.position.y > thumbMcp.position.y + 0.05;
        const indexDown = indexTip.position.y < thumbMcp.position.y;
        
        const detected = thumbUp && indexDown;
        
        return {
            detected,
            confidence: detected ? 0.8 : 0,
            position: thumbTip.position.clone()
        };
    }
    
    detectPeaceGesture(joints, pose) {
        // 简化的V字手势检测
        const indexTip = joints.get('index-finger-tip');
        const middleTip = joints.get('middle-finger-tip');
        const ringTip = joints.get('ring-finger-tip');
        const wrist = joints.get('wrist');
        
        if (!indexTip || !middleTip || !ringTip || !wrist) {
            return { detected: false };
        }
        
        // 检查食指和中指伸展，无名指弯曲
        const indexExtended = indexTip.position.distanceTo(wrist.position) > 0.08;
        const middleExtended = middleTip.position.distanceTo(wrist.position) > 0.08;
        const ringBent = ringTip.position.distanceTo(wrist.position) < 0.06;
        
        const detected = indexExtended && middleExtended && ringBent;
        
        return {
            detected,
            confidence: detected ? 0.8 : 0,
            position: indexTip.position.clone().lerp(middleTip.position, 0.5)
        };
    }
    
    detectFistGesture(joints, pose) {
        // 简化的拳头检测
        const wrist = joints.get('wrist');
        const fingerTips = [
            joints.get('index-finger-tip'),
            joints.get('middle-finger-tip'),
            joints.get('ring-finger-tip'),
            joints.get('pinky-finger-tip')
        ];
        
        if (!wrist || fingerTips.some(tip => !tip)) {
            return { detected: false };
        }
        
        // 检查所有手指是否都弯曲
        const allBent = fingerTips.every(tip => 
            tip.position.distanceTo(wrist.position) < 0.05
        );
        
        return {
            detected: allBent,
            confidence: allBent ? 0.8 : 0,
            position: wrist.position.clone()
        };
    }
    
    detectOKGesture(joints, pose) {
        // 简化的OK手势检测
        const thumbTip = joints.get('thumb-tip');
        const indexTip = joints.get('index-finger-tip');
        const middleTip = joints.get('middle-finger-tip');
        
        if (!thumbTip || !indexTip || !middleTip) {
            return { detected: false };
        }
        
        // 检查拇指和食指形成圆圈，中指伸展
        const thumbIndexDistance = thumbTip.position.distanceTo(indexTip.position);
        const circleFormed = thumbIndexDistance < 0.03;
        const middleExtended = middleTip.position.y > indexTip.position.y + 0.02;
        
        const detected = circleFormed && middleExtended;
        
        return {
            detected,
            confidence: detected ? 0.8 : 0,
            position: thumbTip.position.clone().lerp(indexTip.position, 0.5)
        };
    }
    
    processGesture(gestureType, handedness, gestureData, joints) {
        // 创建手势事件
        const gestureEvent = {
            type: gestureType,
            handedness,
            data: gestureData,
            joints,
            timestamp: Date.now()
        };
        
        // 添加到历史记录
        this.gestureHistory.push(gestureEvent);
        
        // 限制历史记录长度
        if (this.gestureHistory.length > 100) {
            this.gestureHistory.shift();
        }
        
        // 调用注册的处理器
        this.callGestureHandlers(gestureType, gestureEvent);
        
        // 触发XR管理器事件
        this.xrManager.dispatchEvent('gesture-detected', gestureEvent);
    }
    
    callGestureHandlers(gestureType, gestureEvent) {
        if (this.gestureCallbacks.has(gestureType)) {
            this.gestureCallbacks.get(gestureType).forEach(handler => {
                try {
                    handler(gestureEvent);
                } catch (error) {
                    console.error(`手势处理器错误 (${gestureType}):`, error);
                }
            });
        }
    }
    
    // 默认手势处理器
    handlePinchGesture(gesture) {
        console.log('👌 处理捏合手势', gesture.handedness);
        
        // 执行空间选择
        if (gesture.data.position) {
            const direction = new THREE.Vector3(0, 0, -1);
            const intersects = this.xrManager.performRaycast(gesture.data.position, direction);
            
            if (intersects.length > 0) {
                this.xrManager.selectObject(intersects[0].object, `pinch-${gesture.handedness}`);
            }
        }
        
        // 触发触觉反馈
        if (this.options.enableHapticFeedback) {
            this.triggerHapticFeedback(gesture.handedness, 'pinch');
        }
    }
    
    handlePointGesture(gesture) {
        console.log('👉 处理指向手势', gesture.handedness);
        
        // 执行空间指向
        if (gesture.data.position && gesture.data.direction) {
            const intersects = this.xrManager.performRaycast(gesture.data.position, gesture.data.direction);
            
            if (intersects.length > 0) {
                // 高亮指向的对象
                this.highlightObject(intersects[0].object);
            }
        }
    }
    
    handlePalmGesture(gesture) {
        console.log('✋ 处理手掌手势', gesture.handedness);
        
        // 执行停止操作
        this.xrManager.dispatchEvent('palm-gesture', gesture);
    }
    
    handleSwipeGesture(gesture) {
        console.log('👋 处理滑动手势', gesture.handedness, gesture.data.direction);
        
        // 根据滑动方向执行不同操作
        this.xrManager.dispatchEvent('swipe-gesture', gesture);
    }
    
    handleTapGesture(gesture) {
        console.log('👆 处理点击手势', gesture.handedness);
        
        // 执行点击操作
        this.xrManager.dispatchEvent('tap-gesture', gesture);
    }
    
    handleThumbsUpGesture(gesture) {
        console.log('👍 处理竖拇指手势', gesture.handedness);
        
        // 表示赞同或确认
        this.xrManager.dispatchEvent('thumbsup-gesture', gesture);
    }
    
    handlePeaceGesture(gesture) {
        console.log('✌️ 处理V字手势', gesture.handedness);
        
        // 表示和平或胜利
        this.xrManager.dispatchEvent('peace-gesture', gesture);
    }
    
    handleFistGesture(gesture) {
        console.log('✊ 处理拳头手势', gesture.handedness);
        
        // 表示力量或抓取
        this.xrManager.dispatchEvent('fist-gesture', gesture);
    }
    
    handleOKGesture(gesture) {
        console.log('👌 处理OK手势', gesture.handedness);
        
        // 表示确认或同意
        this.xrManager.dispatchEvent('ok-gesture', gesture);
    }
    
    // 辅助方法
    triggerHapticFeedback(handedness, gestureType) {
        // 简化的触觉反馈
        console.log(`触觉反馈: ${gestureType} on ${handedness} hand`);
    }
    
    highlightObject(object) {
        // 简化的对象高亮
        console.log('高亮对象:', object);
    }
    
    updateVisualFeedback() {
        // 更新可视化反馈
        // 实际实现会更复杂
    }
    
    /**
     * 主要更新方法 - 每帧调用
     * @param {number} delta - 时间增量
     */
    update(delta) {
        if (!this.xrManager || !this.xrManager.isXRActive) {
            return;
        }
        
        try {
            // 更新手部数据
            this.updateHandData();
            
            // 识别手势
            this.recognizeGestures();
            
            // 更新视觉反馈
            if (this.options.enableVisualFeedback && this.shouldUpdateVisualization()) {
                this.updateVisualFeedback();
            }
            
            // 清理过期的手势历史
            this.cleanupGestureHistory();
            
        } catch (error) {
            console.warn('手势处理更新过程中出现错误:', error);
        }
    }
    
    /**
     * 清理过期的手势历史记录
     */
    cleanupGestureHistory() {
        const now = performance.now();
        const maxAge = 5000; // 5秒
        
        this.gestureHistory = this.gestureHistory.filter(gesture => {
            return (now - gesture.timestamp) < maxAge;
        });
        
        // 限制历史记录数量
        if (this.gestureHistory.length > 100) {
            this.gestureHistory = this.gestureHistory.slice(-50);
        }
    }
    
    /**
     * 检查是否应该更新可视化
     * @returns {boolean}
     */
    shouldUpdateVisualization() {
        return this.frameCount % 2 === 0; // 每两帧更新一次
    }
    
    // 获取手势历史
    getGestureHistory(gestureType = null, handedness = null, limit = 10) {
        let filtered = this.gestureHistory;
        
        if (gestureType) {
            filtered = filtered.filter(g => g.type === gestureType);
        }
        
        if (handedness) {
            filtered = filtered.filter(g => g.handedness === handedness);
        }
        
        return filtered.slice(-limit);
    }
    
    // 清理资源
    dispose() {
        console.log('🧹 清理统一手势处理器');
        
        this.stopGestureRecognition();
        this.gestureCallbacks.clear();
        this.gestureStates.clear();
        this.gestureHistory = [];
        this.activeGestures.clear();
    }
}